import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/model/useInfo_model.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/firebase_options.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video_page.dart';

class FirebaseMessagingService {
  static final FirebaseMessagingService _instance =
      FirebaseMessagingService._internal();
  factory FirebaseMessagingService() => _instance;
  FirebaseMessagingService._internal();

  late AndroidNotificationChannel channel;
  bool _isInitialized = false;
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();
  // 延迟初始化FirebaseMessaging，不在这里直接实例化
  late FirebaseMessaging _firebaseMessaging;
  // 初始化Firebase消息服务
  Future<void> initialize() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    _firebaseMessaging = FirebaseMessaging.instance;

    await _setupNotifications();
    await _requestPermissions();
    await _getTokens();
    _setupMessageListeners();
  }

  // 配置通知渠道和插件
  Future<void> _setupNotifications() async {
    if (_isInitialized) return;

    channel = const AndroidNotificationChannel(
      'high_importance_channel',
      'High Importance Notifications',
      description: 'This channel is used for important notifications.',
      importance: Importance.high,
    );

    await _notificationsPlugin
        .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin
        >()
        ?.createNotificationChannel(channel);

    await _firebaseMessaging.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    _isInitialized = true;
  }

  // 请求通知权限
  Future<void> _requestPermissions() async {
    final notificationSettings = await _firebaseMessaging.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: true,
      criticalAlert: true,
      provisional: true,
      sound: true,
    );
    debugPrint(
      'Notification permissions granted: ${notificationSettings.authorizationStatus}',
    );
  }

  // 获取设备令牌
  Future<void> _getTokens() async {
    // 获取APNS令牌(iOS)
    if (Platform.isIOS) {
      final apnsToken = await _firebaseMessaging.getAPNSToken();
      if (apnsToken != null) {
        debugPrint('APNS Token: $apnsToken');
      }
    }

    // 获取FCM令牌
    final fcmToken = await _firebaseMessaging.getToken();
    if (fcmToken != null) {
      debugPrint("FCM 令牌: $fcmToken");
      await _updateServerToken(fcmToken);
    } else {
      debugPrint("未能获取 FCM 令牌");
    }

    // 监听令牌刷新
    _firebaseMessaging.onTokenRefresh.listen(_updateServerToken).onError((err) {
      debugPrint("获取令牌错误: $err");
    });
  }

  // 配置消息监听器
  void _setupMessageListeners() {
    // 后台消息处理
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    // 前台消息处理
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      debugPrint('前台收到消息: ${message.data}');
      _showNotification(message);

      if (message.notification != null) {
        debugPrint(
          '通知内容: ${message.notification!.title} - ${message.notification!.body}',
        );
      }
    });

    // 消息打开应用处理
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      debugPrint('通过消息打开应用');
      if (message.data.containsKey('target')) {
        _handleUri(Uri.parse(message.data['target']));
      }
    });

    // 应用启动时的初始消息
    _firebaseMessaging.getInitialMessage().then((initialMessage) {
      if (initialMessage != null) {
        debugPrint('应用启动时的初始消息: ${initialMessage.data}');
      }
    });
  }

  // 显示本地通知
  void _showNotification(RemoteMessage message) {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    if (notification != null && android != null && !kIsWeb) {
      _notificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel.id,
            channel.name,
            channelDescription: channel.description,
            icon: 'launch_background',
          ),
        ),
      );
    }
  }

  // 处理URI导航
  void _handleUri(Uri uri) {
    if (uri.path == '/video/player') {
      String? dramaId = uri.queryParameters['id'];
      if (dramaId != null) {
        int? id = int.tryParse(dramaId);
        if (id != null) {
          VideoModel tempModel = VideoModel(id: id);
          Get.to(
            () => ShortVideoPage(
              preload: false,
              isforyouPage: false,
              superModel: tempModel,
            ),
          );
        } else {
          debugPrint('id 参数不是有效数字: $dramaId');
        }
      } else {
        debugPrint('缺少 id 参数');
      }
    }
  }

  // 更新服务器令牌
  Future<void> _updateServerToken(String token) async {
    // 这里假设UserInfo是全局可访问的
    if (UserInfo().token.isNotEmpty) {
      await UserAPI.set_user_push_token(push_token: token);
    }
  }
}

// 后台消息处理回调
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await FirebaseMessagingService()._setupNotifications();
  FirebaseMessagingService()._showNotification(message);
  debugPrint('Handling a background message ${message.messageId}');
}
